package com.guiji.quartz.task;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: cms-vue-plus
 * @description:
 * @author: gaoX
 * @create: 2021-09-29 10:50
 **/
@Component("monitorEs")
public class MonitorEs {
	private static final String INDEX = "metricbeat-7.12.0-2021.09.22-000001";

	@Autowired
	RestHighLevelClient restHighLevelClient;

	public void query() throws IOException {
		DateTime offset = DateUtil.offset(new Date(), DateField.MINUTE, -481);
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
		String t = df.format(offset);

		SearchRequest searchRequest = new SearchRequest(INDEX);
		BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
		List<QueryBuilder> must = boolQueryBuilder.must();
		must.add(QueryBuilders.matchQuery("metricset.name", "filesystem"));
		must.add(QueryBuilders.matchQuery("system.filesystem.mount_point", "/"));
		List<QueryBuilder> filter = boolQueryBuilder.filter();
		filter.add(QueryBuilders.rangeQuery("@timestamp").gte(t));

		SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
		searchSourceBuilder.query(boolQueryBuilder).size(2000);
		searchSourceBuilder.fetchSource(new String[]{"system.filesystem.used.pct", "system.filesystem.used.bytes", "host.hostname"}, new String[]{});
		searchRequest.source(searchSourceBuilder);
		SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
		// 搜索结果
		SearchHits hits = response.getHits();
		for (SearchHit hit : hits.getHits()) {
			// 源文档的内容
			Map<String, Object> sourceMap = hit.getSourceAsMap();
			Double f = null;
			try {
				f = (Double) ((Map) ((Map) ((Map) sourceMap.get("system")).get("filesystem")).get("used")).get("pct");
			} catch (Exception e) {
				//f=0时报错，继续循环
				continue;
			}
			if (f > 0.8D) {
				//向钉钉发送报警信息
				pushWarn(sourceMap.get("system").toString() + sourceMap.get("host").toString());
				break;
			}

		}

	}

	public void pushWarn(String content) {
		Map<String, Object> param = new HashMap<>();
		Map<String, Object> markdown = new HashMap<>();
		String markdown1 = getMarkdown(content);
		markdown.put("title", "统计报告");
		markdown.put("text", markdown1);
		param.put("msgtype", "markdown");
		param.put("markdown", markdown);
		System.out.println("发送钉钉消息成功");
		HttpUtil.post(CountNewsTask.pushUrl, JSONUtil.toJsonStr(param), 10000);
	}

	public String getMarkdown(String content) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String t = sdf.format(new Date());
		StringBuffer stringBuffer = new StringBuffer();
		stringBuffer.append("## " + t + "节点挂载监控警告\n" + content + "\n");
		stringBuffer.append("> ![screenshot](https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.zcool.cn%2Fcommunity%2F01e37d5854d68aa8012060c811ff4a.jpg%402o.jpg&refer=http%3A%2F%2Fimg.zcool.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1635578831&t=6ed8599b15e3fd401929ce9ae5795a4b)");
		return stringBuffer.toString();
	}
}
